package com.crossriver.crgis.portlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;

import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class PublicDownloadTarrifs
 */
public class PublicDownloadTarrifs extends MVCPortlet {
 
	  public void serveResource (
	    		ResourceRequest resReq, ResourceResponse resRes)
	    throws IOException, PortletException
	    {
	    	
	    	HttpServletRequest convertReq = PortalUtil.getHttpServletRequest(resReq);
	    	HttpServletRequest originalReq = PortalUtil.getOriginalServletRequest(convertReq);
	    	      
	     	//get the download type
	    	String downloadType = resReq.getParameter("downloadType");
	    	if("static".equalsIgnoreCase(downloadType)){
	    		String staticFileLoc = this.getInitParameter("static-file-location");
	        	
	        	String fileNameToDownload = resReq.getParameter("fileName"); //originalReq.getParameter("_Download_fileName");
	        	
	        	System.out.println("fileNameToDownload new --->>>" + resReq.getParameter("fileName"));
	        	
	        	File newFile = new File( staticFileLoc + "//" + fileNameToDownload + ".pdf");
	        	 
	        	resRes.setContentType("application/pdf");
	        	resRes.setContentLength((int) newFile.length());
	        	
	        	String newReplaced = fileNameToDownload.replaceAll(" ", "");
	        	
	        	resRes.setProperty("Content-Disposition", "attachment; filename=" + newReplaced +".pdf");
	        	
	        	FileInputStream fis = new FileInputStream (newFile) ;
	        	
	        	byte[] readStream = new byte [(int) newFile.length()];
	    		fis.read(readStream );
	        	
	        	resRes.getPortletOutputStream().write(readStream);
	        	
	        	fis.close();
	    	}
	    	
	    }
}
